package com.matol.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/*
 * 使用Spring的AOP切面拦截器
 */
public class SystemInterceptor extends HandlerInterceptorAdapter {  
	//业务处理器处理请求之前被调用
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){  
    	try {
			HandlerMethod handlerMethod = (HandlerMethod) handler;  
			//System.out.println(handlerMethod.getMethod().getName());
			//System.out.println(request.getContextPath());
			
			Object obj = request.getSession().getAttribute("loginedUser");
			if("getAllUser".equals(handlerMethod.getMethod().getName())){
				if(obj == null){
					// 如果session中不存在登录者实体，则弹出框提示重新登录  
					request.setCharacterEncoding("UTF-8");  
			        response.setCharacterEncoding("UTF-8");  
			        response.setContentType("text/html;charset=UTF-8");
			        
			        PrintWriter out = response.getWriter();  
                    StringBuilder builder = new StringBuilder();  
                    builder.append("<script type=\"text/javascript\" charset=\"UTF-8\">");  
                    builder.append("alert(\"没有登录或页面过期，请重新登录\");");  
                    builder.append("window.top.location.href=\"");  
                    builder.append(request.getContextPath());  //项目名称路径
                    builder.append("/user/toLogin\";</script>");  
                    out.print(builder.toString());  
                    out.close();
			        
                    return false; //中断后去业务处理  
				}else{
					//存在会话，直接登录
					//response.sendRedirect(request.getContextPath()+"/user/list");
					//return false; //中断后去业务处理 
				}
			}
			
			//logs日志
			//数据合法性校验
			
    	} catch (Exception e) { Tools.Logs("##[preHandle]##"+e.getMessage()); } 
        
    	return true;
    }  
  
    //业务处理器处理完请求后，但是DispatcherServlet向客户端返回请求前被调用
    public void postHandle(  
            HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)  
            throws Exception {  
    }  
  
    //DispatcherServlet完全处理完请求后被调用，可以在该方法中进行一些资源清理的操作
    public void afterCompletion(  
            HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)  
            throws Exception {  
    }  
}  
